package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.dao.BspsMchntBaseInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsUserInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntBaseInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsUserInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.MchntBaseInfo;
import cc.rengu.igas.bsps.common.entity.MchntBindInfo;
import cc.rengu.igas.bsps.common.entity.UserInfo;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.realize.PublicDealService;
import cc.rengu.igas.bsps.core.realize.impl.PublicDealServiceImpl;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.bean.CashierInfoBean;
import cc.rengu.igas.bsps.facade.request.MchntCashierListQueryRequest;
import cc.rengu.igas.bsps.facade.response.MchntCashierListQueryResponse;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 收银员列表查询
 * Created by 王成 on 2018/7/26.
 * update by 赵奎伍 on 2020/04/06
 *
 * @author zhangxuran (需要改联调)
 * @version 1.0
 * @date 2020.04.06
 */
public class MchntCashierListQueryService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        MchntCashierListQueryRequest mchntCashierListQueryRequest = new MchntCashierListQueryRequest();
        ConvertUtil.convertOutput(mchntCashierListQueryRequest);
        return mchntCashierListQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        MchntCashierListQueryRequest requestParams = (MchntCashierListQueryRequest) request;
        MchntCashierListQueryResponse responseParams = new MchntCashierListQueryResponse();
        rglog.info("收银员查询交易");
        String userId = requestParams.getUserId();
        String mchntNo = requestParams.getMchntNo();
        String queryMchntNo = requestParams.getQueryMchntNo();
        String instId = requestParams.getHeader().getInstId();
        String channelId = requestParams.getHeader().getChanlId();
        rglog.info("必填性校验");
        if (StringUtil.isEmptyOrNull(mchntNo) || StringUtil.isEmptyOrNull(instId) || (!"MOBILE".equals(channelId) && StringUtil.isEmptyOrNull(userId))) {
            rglog.error("必填性信息校验失败");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }


        PublicDealService publicDealService = new PublicDealServiceImpl();
        List<MchntBindInfo> mchntBindInfoList = publicDealService.mchntCashierListQuery(instId, mchntNo, userId);

        /*
         *当门店商户号queryMchntNo非空时进行过滤
         * */
        rglog.info("queryMchntNo:" + queryMchntNo);
        if (!StringUtil.isEmptyOrNull(queryMchntNo) && !CollectionUtils.isEmpty(mchntBindInfoList)) {
            rglog.info("查询连锁商户门店收银员列表");
            mchntBindInfoList = mchntBindInfoList.stream().filter(item -> queryMchntNo.equals(item.getMchntNo())).collect(Collectors.toList());
        }

        List<CashierInfoBean> cashierInfoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(mchntBindInfoList)) {
            mchntBindInfoList.forEach(item -> convMchntBindInfo(item, cashierInfoList, channelId));
        }
        responseParams.setCashierInfoList(cashierInfoList);
        /* 组装应答报文 */
        BizResponse<MchntCashierListQueryResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(responseParams);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        MchntCashierListQueryResponse mchntCashierListQueryResponse = (MchntCashierListQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(mchntCashierListQueryResponse);
    }

    /**
     * 将数据库表结构对象转换成接口对象
     *
     * @param mchntBindInfo 数据库表结构对象
     * @param cashierInfos  接口对象
     */
    private void convMchntBindInfo(MchntBindInfo mchntBindInfo, List<CashierInfoBean> cashierInfos, String channelId) {
        CashierInfoBean cashierInfo = new CashierInfoBean();
        //收银员标识
        cashierInfo.setCashierId(mchntBindInfo.getBindUserId());
        //收银员昵称
        cashierInfo.setUserNickName(mchntBindInfo.getBindNickName());
        //所属商户/门店
        cashierInfo.setMchntNo(mchntBindInfo.getMchntNo());
        //商户类型
        cashierInfo.setMchntType(mchntBindInfo.getBindMchntType());
        //收银员角色
        cashierInfo.setBindUserRole(mchntBindInfo.getBindUserRole());
        //绑定状态
        cashierInfo.setBindStatus(mchntBindInfo.getBindStatus());
        //关联收银员
        cashierInfo.setMsgPushUsers(mchntBindInfo.getMsgPushUsers());
        //连锁商户号
        cashierInfo.setChainMchntNo(mchntBindInfo.getChainMchntNo());
        String remark1 = mchntBindInfo.getRemark1();
        if (!StringUtil.isEmptyOrNull(remark1)) {
            Map<String, Object> reqMap = JSONObject.parseObject(remark1);
            if (reqMap != null && reqMap.get("adminAuth") != null && !"".equals(reqMap.get("adminAuth"))) {
                //查询交易权限
                String adminAuth = "00";
                if (String.valueOf(reqMap.get("adminAuth")).equals("Y")) {
                    adminAuth = "01";
                }

                cashierInfo.setTransInfoQueryAuth(adminAuth);
            }

        }

//        if(!"MOBILE".equals(channelId)){
        try {
            //根据用户标识去用户信息表查找 收银员手机号
            BspsUserInfoMapper userInfoMapper = new BspsUserInfoMapperImpl();
            UserInfo userInfo = userInfoMapper.selectBspsUserInfoByUserId(mchntBindInfo.getInstId(), mchntBindInfo.getBindUserId());
            if (null != userInfo) {
                //收银员名称
                cashierInfo.setUserName(userInfo.getUserName());
                //收银员手机号
                cashierInfo.setMobileNo(userInfo.getMobileNo());
                //收银员账号
                cashierInfo.setCashierUserLoginId(userInfo.getUserLoginId());
                //收银员微信号
                cashierInfo.setCashierUserOpenId(userInfo.getOpenId());
            }
            //根据商户号去上户基本信息表查找 商户名称
            BspsMchntBaseInfoMapper bspsMchntBaseInfoMapper = new BspsMchntBaseInfoMapperImpl();
            MchntBaseInfo mchntBaseInfo = bspsMchntBaseInfoMapper.selectBspsMchntBaseInfoByPrimaryKey(mchntBindInfo.getInstId(), mchntBindInfo.getMchntNo());
            if (null != mchntBaseInfo) {
                cashierInfo.setMchntName(mchntBaseInfo.getMchntName());

            }
        } catch (Exception e) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            e.printStackTrace(new PrintWriter(byteArrayOutputStream, true));
            rglog.error("转换收银台应答信息异常,异常信息:<{}>", byteArrayOutputStream.toString());
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
//        }
        cashierInfos.add(cashierInfo);
    }

}
